package org.monster.context.core.communicator;

import org.monster.context.core.manager.StringManager;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 通信器线程
 *
 * @author Monster
 */
public class CommunicatorThread extends Thread {

    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(CommunicatorThreadPool.class
            .getName());
    /**
     * 字符串管理器
     */
    private static final StringManager sm = StringManager.getManager(Constants.Package);
    /**
     * 通讯器池
     */
    private final CommunicatorThreadPool pool;
    /**
     * 通讯器
     */
    private Communicator communicator;
    /**
     * 阻塞状态
     */
    private volatile boolean blocked;
    /**
     * 可运行状态
     */
    private volatile boolean runnable;

    /**
     * 构造方法
     *
     * @param pool 通讯池
     */
    public CommunicatorThread(CommunicatorThreadPool pool) {
        this.pool = pool;
    }

    /**
     * 将通信器放入容器
     *
     * @param communicator 通信器
     */
    public void setCommunicator(Communicator communicator) {
        this.communicator = communicator;
    }

    /**
     * 是否 阻塞状态
     *
     * @return 阻塞状态
     */
    public boolean isBlocked() {
        return blocked;
    }

    /**
     * 设置 阻塞状态
     *
     * @param blocked 阻塞状态
     */
    public void setBlocked(boolean blocked) {
        this.blocked = blocked;
    }

    /**
     * 是否 可运行状态
     *
     * @return 可运行状态
     */
    public boolean isRunnable() {
        return runnable;
    }

    /**
     * 设置 可运行状态
     *
     * @param runnable 可运行状态
     */
    public void setRunnable(boolean runnable) {
        this.runnable = runnable;
    }

    /**
     * 运行
     */
    @Override
    public synchronized void run() {
        try {
            //循环执行，进行重用
            while (true) {
                //如果线程是可运行状态
                if (isRunnable()) {
                    //线程执行
                    communicator.receive();
                    //执行完，将当前线程插入线程池队列前面
                    pool.pushCommunicatorThread(this);
                }
                //设置线程阻塞状态
                setBlocked(true);
                //线程等待队列
                this.wait();
            }
        } catch (InterruptedException e) {
            logger.log(Level.SEVERE,
                    sm.getString("communicatorThread.interruptedException"));
        }
    }

    /**
     * 重新启动
     *
     * @param communicator 通信器
     */
    public synchronized void restart(Communicator communicator) {
        //设置通讯器
        setCommunicator(communicator);
        //设置线程可运行状态
        setRunnable(true);
        //通知唤醒当前线程
        this.notify();
    }
}
